package cn.niceff.middleware.dynamic.thread.pool.sdk.trigger.listener;

import cn.niceff.middleware.dynamic.thread.pool.sdk.domain.IPoolService;
import cn.niceff.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.niceff.middleware.dynamic.thread.pool.sdk.registry.IRegistry;
import com.alibaba.fastjson.JSON;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author niceff.cn
 * @apiNote 线程池配置监听器, 用于监听redis发来的请求, 并做出响应
 */
public class ThreadPoolConfigListener implements MessageListener<ThreadPoolConfigEntity> {
    private Logger log = LoggerFactory.getLogger(ThreadPoolConfigListener.class);

    private final IPoolService poolService;

    private final IRegistry registry;

    public ThreadPoolConfigListener(IPoolService poolService, IRegistry registry) {
        this.poolService = poolService;
        this.registry = registry;
    }

    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity entity) {
        log.info("收到线程池配置变更请求, 开始处理.., 实例数据如下:{}", JSON.toJSONString(entity));
        // 更新本地配置
        poolService.updateThreadPoolConfig(entity);
        // 上报最新数据
        // 查询list
        List<ThreadPoolConfigEntity> threadPoolConfigEntities = poolService.queryThreadPoolList();
        // 上报list
        registry.reportThreadPool(threadPoolConfigEntities);
        ThreadPoolConfigEntity current = poolService.queryThreadPoolConfigByName(entity.getThreadPoolName());
        // 更新单条
        registry.reportThreadPoolConfigParameter(current);
        log.info("动态线程池，上报线程池配置：{}", JSON.toJSONString(entity));
    }
}
